﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using Dashboard.ProductBonus.Business;
using Infragistics.Win;
using Infragistics.Win.UltraWinGrid;

namespace Dashboard.ProductBonus
{
    public partial class FormDailyAttendanceReport : Form
    {
        public FormDailyAttendanceReport()
        {
            InitializeComponent();
        }

        private void FormDailyAttendanceReport_Load(object sender, EventArgs e)
        {
            this.SetDefaultDateFromTo();
            this.BindTeamList();
        }

        private void comboBoxTeam_SelectedIndexChanged(object sender, EventArgs e)
        {
            this.BindShift();
        }

        private void comboBoxShift_SelectedIndexChanged(object sender, EventArgs e)
        {
            this.BindStaffNoList();
        }

        private void toolStripButtonQuery_Click(object sender, EventArgs e)
        {
            try
            {
                this.Cursor = Cursors.WaitCursor;

                this.ultraGridMain.DataSource = null;
                this.ultraGridMain.ResetDisplayLayout();
                this.ultraGridMain.Layouts.Clear();

                this.BindGrid();
            }
            catch (Exception ex)
            {
                MessageBox.Show(this, ex.Message, "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
            finally
            {
                this.Cursor = Cursors.Default;
            }
        }

        private void BindGrid()
        {
            var dateTimeFrom = this.dateTimePickerFrom.Value.Date;
            var dateTimeTo = this.dateTimePickerTo.Value.Date;
            if (dateTimeTo < dateTimeFrom)
            {
                MessageBox.Show(this, "Date to can not earlier than Date from.", "Info", MessageBoxButtons.OK, MessageBoxIcon.Information);
                this.dateTimePickerTo.Focus();
                return;
            }

            AttendanceReport ar = new AttendanceReport();

            // 获取符合条件的所有的用户列表
            DataTable staffList = ar.GetAttendanceReportStaffList(this.dateTimePickerFrom.Value.Date,
                                                              this.dateTimePickerTo.Value.Date,
                                                              this.comboBoxTeam.Text,
                                                              this.comboBoxShift.Text,
                                                              (this.comboBoxStaffNo.Text == "" ? "" : this.comboBoxStaffNo.Text.Split('-')[0]));
            // 获取所有的请假记录
            DataTable absentList = ar.GetAllAbsentRecord(this.dateTimePickerFrom.Value.Date,
                                                              this.dateTimePickerTo.Value.Date,
                                                              this.comboBoxTeam.Text,
                                                              this.comboBoxShift.Text,
                                                              (this.comboBoxStaffNo.Text == "" ? "" : this.comboBoxStaffNo.Text.Split('-')[0]));
                       
            DataTable finalDT = staffList.DefaultView.ToTable(true, new string[] { "StaffNo", "Name", "Dept", "Team", "Shift" });           
        
            int days = dateTimeTo.Subtract(dateTimeFrom.Date).Days;

            for (int i = 0; i <= days; i++)
            {
                finalDT.Columns.Add(dateTimeFrom.AddDays(i).Date.ToString("yyyy-MM-dd"), typeof(string));
            }
            finalDT.AcceptChanges();

            // 根据查询出来的数据，获取对应天的信息
            foreach (DataRow row in finalDT.Rows)
            {
                for (int i = 5; i < finalDT.Columns.Count; i++)
                {
                    string filterString = string.Format("StaffNo='{0}' AND Date='{1}'", row["StaffNo"].ToString(), finalDT.Columns[i].ColumnName);
                    DataRow[] record = staffList.Select(filterString);
                    if (record.Length == 0)
                    {
                        // 没有排班，或者这天是周末
                        DateTime colName = DateTime.ParseExact(finalDT.Columns[i].ColumnName, "yyyy-MM-dd", null);
                        if (colName.DayOfWeek == DayOfWeek.Sunday || colName.DayOfWeek == DayOfWeek.Saturday)
                        {
                            row[i] = "S";
                        }
                        else
                        {
                            row[i] = "-";
                        }
                    }
                    else
                    {
                        if (record[0]["Onduty"].ToString() == "Y")
                        {
                            if (record[0]["WorkingShift"].ToString() == "-1") // 没有排班，但有打卡记录，显示绿色
                            {
                                row[i] = "G";
                            }
                            else
                            {
                                row[i] = "B";   // 有排班且有打卡记录，则显示蓝色
                            }
                            
                        }
                        else  // 没有打卡记录
                        {
                            if (record[0]["WorkingShift"].ToString() == "-1") // 没有排班，且没有打卡记录，则显示S
                            {
                                row[i] = "S";
                            }
                            else   // 有排班，但没有打卡记录，显示橘黄色
                            {
                                row[i] = "O";
                            }
                        }
                    }

                    record = absentList.Select(filterString);
                    if (record.Length > 0)
                    {
                        foreach (DataRow item in record)
                        {
                            row[i] += item["ReasonCode"].ToString() + "(" + item["TotalTime"].ToString() + ")";
                        }                        
                    }
                }
            }

            finalDT.AcceptChanges();

            this.ultraGridMain.DataSource = finalDT;
            this.ultraGridMain.DataBind();

            if (this.ultraGridMain.Rows.Count > 0)
            {
                this.toolStripButtonExport.Enabled = true;
            }
        }

        private void toolStripButtonExport_Click(object sender, EventArgs e)
        {
            var dialogResult = this.saveFileDialogMain.ShowDialog();
            if (dialogResult == DialogResult.OK)
            {
                var fileName = this.saveFileDialogMain.FileName;
                this.ultraGridExcelExporterMain.Export(this.ultraGridMain, fileName);
                MessageBox.Show("Export data successfully!", "Information", MessageBoxButtons.OK,
                                MessageBoxIcon.Information);
            }
        }

        private void toolStripButtonExit_Click(object sender, EventArgs e)
        {
            this.Close();
        }

        private void BindTeamList()
        {
            BusinessBase bb = new BusinessBase();
            DataTable teams = bb.LoadTeamList();

            this.comboBoxTeam.Items.Clear();
            this.comboBoxTeam.Items.Add("");

            foreach (DataRow row in teams.Rows)
            {
                this.comboBoxTeam.Items.Add(row["team"].ToString());
            }

            if (this.comboBoxTeam.Items.Count > 0)
            {
                this.comboBoxTeam.SelectedIndex = 0;
            }

            bb = null;
        }

        private void BindShift()
        {
            BusinessBase bb = new BusinessBase();
            DataTable result = bb.LoadTeamShiftList(this.comboBoxTeam.Text);

            this.comboBoxShift.Items.Clear();
            this.comboBoxShift.Items.Add("");

            foreach (DataRow row in result.Rows)
            {
                this.comboBoxShift.Items.Add(row["Shift"].ToString());
            }
            if (this.comboBoxShift.Items.Count > 0)
            {
                this.comboBoxShift.SelectedIndex = 0;
            }
        }

        private void BindStaffNoList()
        {
            BusinessBase bb = new BusinessBase();
            DataTable staffs = bb.GetStaffOfTeamShift(this.comboBoxTeam.Text, this.comboBoxShift.Text);

            this.comboBoxStaffNo.Items.Clear();
            this.comboBoxStaffNo.Text = string.Empty;
            this.comboBoxStaffNo.Items.Add("");

            foreach (DataRow row in staffs.Rows)
            {
                this.comboBoxStaffNo.Items.Add(row["staffno"].ToString() + "-" + row["name"].ToString());
            }
            if (this.comboBoxStaffNo.Items.Count > 0)
            {
                this.comboBoxStaffNo.SelectedIndex = 0;
            }
            bb = null;
        }

        private void SetDefaultDateFromTo()
        {
            var today = DateTime.Today.Date;
            var monday = today.AddDays(-((int)DateTime.Now.DayOfWeek == 0 ? 7 : (int)DateTime.Now.DayOfWeek)).AddDays(1);
            this.dateTimePickerFrom.Value = monday;
        }

        private void ultraGridMain_InitializeLayout(object sender, Infragistics.Win.UltraWinGrid.InitializeLayoutEventArgs e)
        {
            // 自适应列宽
            e.Layout.AutoFitStyle = Infragistics.Win.UltraWinGrid.AutoFitStyle.None;
            // 是否允许调整列宽
            e.Layout.Override.AllowColSizing = AllowColSizing.Free;
            // 是否允许移动栏位顺序
            e.Layout.Override.AllowColMoving = AllowColMoving.NotAllowed;

            // 设置Grid的Split窗口个数，建议设置为1--不允许Split
            e.Layout.MaxColScrollRegions = 1;
            e.Layout.MaxRowScrollRegions = 1;

            // 冻结列
            e.Layout.UseFixedHeaders = false;

            // 排序
            e.Layout.Override.HeaderClickAction = Infragistics.Win.UltraWinGrid.HeaderClickAction.SortSingle;

            // 不允许删除\更新
            e.Layout.Override.AllowDelete = DefaultableBoolean.False;
            e.Layout.Override.AllowUpdate = DefaultableBoolean.False;
            e.Layout.Override.CellClickAction = CellClickAction.CellSelect;

            e.Layout.Bands[0].HeaderVisible = true;
            e.Layout.Bands[0].Header.Caption = "(Double click on cell to show time card record list.)";
            e.Layout.Bands[0].Header.Appearance.ForeColor = Color.RoyalBlue;
            e.Layout.Bands[0].Header.Appearance.TextHAlign = HAlign.Left;

            // 滚动提示
            e.Layout.Bands[0].ScrollTipField = "StaffNo";

            e.Layout.Bands[0].Columns["StaffNo"].Width = 60;
            e.Layout.Bands[0].Columns["Name"].Width = 100;
            e.Layout.Bands[0].Columns["Dept"].Width = 60;
            e.Layout.Bands[0].Columns["Team"].Width = 60;
            e.Layout.Bands[0].Columns["Shift"].Width = 40;

            for (int i = 0; i < e.Layout.Bands[0].Columns.Count; i++)
            {
                if (i < 5)
                {
                    continue;
                }
                else
                {
                    e.Layout.Bands[0].Columns[i].Width = 50;
                    e.Layout.Bands[0].Columns[i].CellAppearance.TextHAlign = HAlign.Center;

                    var date = e.Layout.Bands[0].Columns[i].Key;
                    DateTime dateTime = DateTime.ParseExact(date, "yyyy-MM-dd", null);
                    e.Layout.Bands[0].Columns[i].Header.Caption = dateTime.ToString("MM/dd");
                }
            }
        }

        private void ultraGridMain_InitializeRow(object sender, InitializeRowEventArgs e)
        {
            if (e.Row.IsDataRow)
            {
                for (int i = 5; i < e.Row.Cells.Count; i++)
                {
                    var cellValue = e.Row.Cells[i].Value.ToString();
                    if (cellValue == "B" || cellValue.StartsWith("B"))
                    {
                        e.Row.Cells[i].Appearance.BackColor = Color.DeepSkyBlue;

                        if (cellValue != "B")
                        {
                            e.Row.Cells[i].Value = cellValue.Substring(1, cellValue.Length - 1);
                        }
                        else
                        {
                            e.Row.Cells[i].Value = string.Empty;
                        }
                    }

                    if (cellValue == "G" || cellValue.StartsWith("G"))
                    {
                        e.Row.Cells[i].Appearance.BackColor = Color.LawnGreen;

                        if (cellValue != "G")
                        {
                            e.Row.Cells[i].Value = cellValue.Substring(1, cellValue.Length - 1);
                        }
                        else
                        {
                            e.Row.Cells[i].Value = string.Empty;
                        }
                    }

                    if (cellValue == "O" || cellValue.StartsWith("O"))
                    {
                        e.Row.Cells[i].Appearance.BackColor = Color.Orange;

                        if (cellValue != "O")
                        {
                            e.Row.Cells[i].Value = cellValue.Substring(1, cellValue.Length - 1);
                        }
                        else
                        {
                            e.Row.Cells[i].Value = string.Empty;
                        }
                    }

                    if (cellValue == "S" || cellValue.StartsWith("S"))
                    {
                        if (cellValue != "S")
                        {
                            e.Row.Cells[i].Value = cellValue.Substring(1, cellValue.Length - 1);
                        }
                    }

                    if (cellValue == "-" || cellValue.StartsWith("-"))
                    {
                        if (cellValue != "-")
                        {
                            e.Row.Cells[i].Value = cellValue.Substring(1, cellValue.Length - 1);
                        }
                        else
                        {
                            e.Row.Cells[i].Value = "-";
                        }
                    }
                }

                e.Row.Update();
            }
        }

        private void ultraGridMain_DoubleClickCell(object sender, DoubleClickCellEventArgs e)
        {
            if (e.Cell.Row.IsDataRow)
            {
                if (e.Cell.Column.Index >= 5)
                {
                    string staffNo = e.Cell.Row.Cells["StaffNo"].Value.ToString();
                    DateTime date = DateTime.ParseExact(e.Cell.Column.Key, "yyyy-MM-dd", null);

                    using (FormTimeCardList ftcl = new FormTimeCardList())
                    {
                        ftcl.StaffNo = staffNo;
                        ftcl.Date = date;

                        ftcl.ShowDialog();
                    }
                }
            }
        }
    }
}
